<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, DesDev, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
class openzcajax{
	
    function ajaxRun($data){
		global $product_class;
		$action=$data['action'];
		
		switch($action){
			case "delCart":
			    if(array_key_exists($data['id'],$_SESSION['cart']->contents)){
				   $_SESSION['cart']->remove($data['id']);
				   $data['status']=true;
			    }
			break;
			case "quantity":
				$stock=zen_get_products_stock($data['id']);
				if(!is_numeric($data['value'])){
					$new_qty=$_SESSION['cart']->get_quantity($data['id']);
				}else{
					$new_qty=$data['value'];
				}
				if($new_qty>=$stock){$new_qty=$stock;}
				$attributes = $_SESSION['cart']->contents[$data['id']]['attributes'] ? $_SESSION['cart']->contents[$data['id']]['attributes'] : '';
				$_SESSION['cart']->add_cart($data['id'], $new_qty, $attributes, false);
				$data['status']=true;
				if($_SESSION['cart_errors']){$data['reload']="#msgOpenzc:msgCart";}
			break;
			case "addOne":
				$new_qty = $this->adjust_quantity($data);
				$attributes = $_SESSION['cart']->contents[$data['id']]['attributes'] ? $_SESSION['cart']->contents[$data['id']]['attributes'] : '';
				$_SESSION['cart']->add_cart($data['id'], $new_qty, $attributes, false);
				$data['status']=true;
			break;
			case "cutOne":
				$cart_qty=$_SESSION['cart']->get_quantity($data['id']);
				if($cart_qty==1){
					$_SESSION['cart']->remove($data['id']);
					$data['status']=true;
				}else{
					$_SESSION['cart']->add_cart($data['id'],$cart_qty, $attributes, false);
					$data['status']=true;
				}
			break;
			case "editCart":
			break;
			case "addCart":
			    $this->addCart($data);
				$data['status']=true;
				if($_SESSION['cart_errors']){$data['reload']="#msgOpenzc:msgCart";}
				
			break;
			case "filterPrice":
				global $currencies;
				if(!isset($_GET['price'])){
					if($data['min']>=$data['max']){
						$data['min']=$data['max']-1;
					}
					$_SESSION["filter_price_min"]=$data['min'];
					$_SESSION["filter_price_max"]=$data['max'];
					if(DEFAULT_CURRENCY!=$_SESSION['currency']){
						$data['min']=round($data['min']/($currencies->currencies[$_SESSION['currency']]['value']),2);
						$data['max']=round($data['max']/($currencies->currencies[$_SESSION['currency']]['value']),2);
					}
					$data['url'].="&price=".$data['min'].",".$data["max"];
					$data['action']="getUrl";
					header('Content-Type:application/json; charset=utf-8');
					echo json_encode($data);
					exit(0);
				}else{
					$data['status']=true;
				}
			break;
			case "getHtml":
				$data['status']=true;
			break;
			case "getState":
				global $variable_class;
				$selected_country=$data['value'];
				$GLOBALS['states'] = $variable_class->get_state_list($selected_country);
				$data['status']=true;
			break;
			case "addWishlist":
				$data['status']=true;
				if(isset($_SESSION['customer_id'])){
					$_SESSION['wishlist']['list'].=",".$data['id'];
					$str=array_unique(array_filter(explode(",",$_SESSION['wishlist']['list'])));
					$_SESSION['wishlist']['list']=join(",",$str);
					$_SESSION['wishlist']['current']=$data['id'];
					$data['reload']="#msgOpenzc:msgWishlist";
				}else{
					$data['reload']="#msgOpenzc:msgLogin";
				}
			break;
			case "delWishlist":
				$data['status']=true;
				if(isset($_SESSION['customer_id'])){
					$list=explode(",",$_SESSION['wishlist']['list']);
					foreach($list as $k => $v){if($v==$data['id']){unset($list[$k]);}}
					$_SESSION['wishlist']['list']=join(",",$list);
					$_SESSION['wishlist']['current']=$data['id'];
					$_SESSION['wishlist']['action']=$action;
					$data['reload']="#msgOpenzc:msgWishlist";
				}else{
					$data['reload']="#msgOpenzc:msgLogin";
				}
			break;
			case "addCompare":
				$data['status']=true;
				$_SESSION['compare']['list'].=",".$data['id'];
				$str=array_unique(array_filter(explode(",",$_SESSION['compare']['list'])));
				$_SESSION['compare']['list']=join(",",$str);
				$_SESSION['compare']['current']=$data['id'];
				$data['reload']="#msgOpenzc:msgCompare";
			break;
			case "delCompare":
				$data['status']=true;
			
				$list=explode(",",$_SESSION['compare']['list']);
				foreach($list as $k => $v){if($v==$data['id']){unset($list[$k]);}}
				$_SESSION['compare']['list']=join(",",$list);
				$_SESSION['compare']['current']=$data['id'];
				$_SESSION['compare']['action']=$action;
				$data['reload']="#msgOpenzc:msgCompare";
			break;
			case "writeReviews":
			
				$data['status']=true;
				if(isset($_SESSION['customer_id'])){
					
					$this->writeReviews($data);
					if($data['reload']){
						$data['reload'].=",#msgOpenzc:msgReviews";
					}else{
						$data['reload']="#msgOpenzc:msgReviews";
					}
					
				}else{
					$data['reload']="#msgOpenzc:msgLogin";
				}
			
			break;
		}
		/*
		if($_SESSION['cart_errors']){
			//$result['errors']=$_SESSION['cart_errors'];
		}
		*/
		$result=$this->getParameter($data);
		$result['action']=$action;
		if(isset($data['autoReload'])){$result['autoReload']=true;}else{$result['autoReload']=false;}
		header('Content-Type:application/json; charset=utf-8');

		echo json_encode($result);
	}
	
	function getParameter($data){
		$reloadID=openzc_field_to_key(array_filter(explode(",",$data['config']["customReloadID"])));
		
		if(!isset($data['reload'])){$data["reload"]="";}
		foreach($data as $k => $v){
			if(($k=="reload") && $data['status']==true){
				if($v){
					$result[$k]=$this->openzcRload($v,$reloadID);
				}else{
					$result[$k]="null";
				}
			}
		}
			
		if(isset($data["position"])){
			$data['position']=str_replace("%3D","=",$data['position']);
			$tmpfile=TEMPLATE_TPL.base64_decode($data['position']);
			$tmpfileOnlyName = preg_replace("/(.*)\//", "", $tmpfile);
		
			$jquery=TPLCACHE_TPL."/".preg_replace("/\.(php|tpl)$/", "_".substr(md5($tmpfile),0,24).'_jquery.inc', $tmpfileOnlyName);
			include($jquery);
			
			if(isset($data["config"]["customReloadJS"])){
				$reloadJS=$data["config"]["customReloadJS"];
				if(isset($data['autoReload']) || $reloadJS['yes']=="all"){
					$reloadJS['no'].=",openzc.js";
				}
				
				foreach($tplJquery as $k => $v){
					@$filename=end(explode("/",$v));
					$yes=$no="";
					if(!isset($reloadJS['yes'])){unset($tplJquery[$k]);}
					if(isset($reloadJS['yes']) && $reloadJS['yes']!="all"){
						$rjs=explode(",",$reloadJS['yes']);
						foreach($rjs as $a => $b){
							if($b==$filename){$yes=true;}
						}
						if($yes!=true)unset($tplJquery[$k]);
					}
					if(isset($reloadJS["no"]) && $reloadJS["no"]!="all" ){
						$rjs=array_filter(explode(",",$reloadJS['no']));
						foreach($rjs as $a => $b){
							if($b==$filename){$no=true;}
						}
						if($no==true)unset($tplJquery[$k]);
					}
				}
			}else{
				$tplJquery=array();
			}
			
			$result['jquery']=$tplJquery;
		}
		
		return $result;
	}
	
	function openzcRload($data,$reloadID=''){
		global $OpenzcTpl;
		$DivID=array_filter(explode(",",$data));
		foreach($DivID as $k => $v){
			ob_start();
			if(strstr($v,":")){
				$v=explode(":",$v);
				$name=$v[1];
				$div=$v[0];
				$divname=str_replace("#","",$div);
				$divname=str_replace(".","",$divname);
			}else{
				$name=$v;
				$div="#".$name;
			}
			if($name=="msgWishlist" || $name=="msgCompare" || $name=="msgLogin" || $name=="msgReviews" || $name=="msgCart"){
				$tpl=str_replace(TEMPLATE_TPL,"",TPL_MODULES)."msgbox/".$name.".tpl";
			}else{
				$tpl=str_replace(TEMPLATE_TPL,"",TPL_AJAX_BOX).$name.".tpl";
			}
			
			$OpenzcTpl->LoadTemplate($tpl);
			ignore_user_abort(true);
			$OpenzcTpl->Display();
			
			$content[$divname]["div"]=$div;
			$content[$divname]["html"]=ob_get_contents();
			
			ob_end_clean();
			if(array_key_exists($divname,$reloadID)){$content[$divname]['custom_status']=true;}else{$content[$divname]['custom_status']=false;}
		
		}
		return $content;
	}
	
	function addCart($data){
		if (isset($data['products_id']) && is_numeric($data['products_id'])) {
			$the_list = '';
			$adjust_max= 'false';
			if (isset($data['id'])) {
				
				foreach ($data['id'] as $key => $value) {
					
					$check = zen_get_attributes_valid($data['products_id'], $key, $value);
					if ($check == false) {
						$the_list .= TEXT_ERROR_OPTION_FOR . '<span class="alertBlack">' . zen_options_name($key) . '</span>' . TEXT_INVALID_SELECTION . '<span class="alertBlack">' . ($value == (int)PRODUCTS_OPTIONS_VALUES_TEXT_ID ? TEXT_INVALID_USER_INPUT : zen_values_name($value)) . '</span>' . '<br />';
					}
				}
			}
			if (!is_numeric($data['cart_quantity']) || $data['cart_quantity'] < 0) {$data['cart_quantity'] = 0;}
			// verify qty to add
			$add_max = zen_get_products_quantity_order_max($data['products_id']);
			$cart_qty = $_SESSION['cart']->in_cart_mixed($data['products_id']);
			$new_qty = $data['cart_quantity'];

			$new_qty = $_SESSION['cart']->adjust_quantity($new_qty, $data['products_id'], 'shopping_cart');

			// bof: adjust new quantity to be same as current in stock
			$chk_current_qty = zen_get_products_stock($data['products_id']);
			if (STOCK_ALLOW_CHECKOUT == 'false' && ($cart_qty + $new_qty > $chk_current_qty)) {
				$new_qty = $chk_current_qty;
			}
			// eof: adjust new quantity to be same as current in stock

			if (($add_max == 1 and $cart_qty == 1)) {
			// do not add
				$new_qty = 0;
				$adjust_max= 'true';
			} else {
				// bof: adjust new quantity to be same as current in stock
				if (STOCK_ALLOW_CHECKOUT == 'false' && ($new_qty + $cart_qty > $chk_current_qty)) {
					$adjust_new_qty = 'true';
					$alter_qty = $chk_current_qty - $cart_qty;
					$new_qty = ($alter_qty > 0 ? $alter_qty : 0);
				}
				// eof: adjust new quantity to be same as current in stock
				// adjust quantity if needed
				if (($new_qty + $cart_qty > $add_max) and $add_max != 0) {
					$adjust_max= 'true';
					$new_qty = $add_max - $cart_qty;
					$_SESSION['cart_errors']['msgAddmax']=$add_max;
				}
			}
			if ((zen_get_products_quantity_order_max($data['products_id']) == 1 && $_SESSION['cart']->in_cart_mixed($data['products_id']) == 1)) {
			// do not add
			} else {
			// process normally
			// bof: set error message
				if ($the_list== '') {
					$real_ids = isset($data['id']) ? $data['id'] : "";
					// do the actual add to cart
					$_SESSION['cart']->add_cart($data['products_id'], $_SESSION['cart']->get_quantity(zen_get_uprid($data['products_id'], $real_ids))+($new_qty), $real_ids);
				} 
			}
		}
    }
	private function writeReviews($data){
		
		global $db,$messageStack;
		if($this->postCheck("writeReviews",$data)){return false;}
		$customer_query = "SELECT customers_firstname, customers_lastname, customers_email_address
                   FROM " . TABLE_CUSTOMERS . "
                   WHERE customers_id = :customersID";
        $customer_query = $db->bindVars($customer_query, ':customersID', $_SESSION['customer_id'], 'integer');
        $customer = $db->Execute($customer_query);
        
		$rating = zen_db_prepare_input($data['rating']);
		$review_text = zen_db_prepare_input($data['review_text']);
		$error = false;
		if (strlen($review_text) < REVIEW_TEXT_MIN_LENGTH) {
	    	$error = true;
	    	$messageStack->add('review_text', JS_REVIEW_TEXT);
		}
		if (($rating < 1) || ($rating > 5)) {
		    $error = true;
		    $messageStack->add('review_rating', JS_REVIEW_RATING);
		}
		if ($error == false) {
		    if (REVIEWS_APPROVAL == '1') {
		      $review_status = '0';
		    } else {
		      $review_status = '1';
		    }
		
		    $sql = "INSERT INTO " . TABLE_REVIEWS . " (products_id, customers_id, customers_name, reviews_rating, date_added, status)
		            VALUES (:productsID, :customersID, :customersName, :rating, now(), " . $review_status . ")";

		    $sql = $db->bindVars($sql, ':productsID', $_GET['products_id'], 'integer');
		    $sql = $db->bindVars($sql, ':customersID', $_SESSION['customer_id'], 'integer');
		    $sql = $db->bindVars($sql, ':customersName', $customer->fields['customers_firstname'] . ' ' . $customer->fields['customers_lastname'], 'string');
		    $sql = $db->bindVars($sql, ':rating', $rating, 'string');
		
		    $db->Execute($sql);
		
		    $insert_id = $db->Insert_ID();
		
		    $sql = "INSERT INTO " . TABLE_REVIEWS_DESCRIPTION . " (reviews_id, languages_id, reviews_text)
		            VALUES (:insertID, :languagesID, :reviewText)";
		
		    $sql = $db->bindVars($sql, ':insertID', $insert_id, 'integer');
		    $sql = $db->bindVars($sql, ':languagesID', $_SESSION['languages_id'], 'integer');
		    $sql = $db->bindVars($sql, ':reviewText', $review_text, 'string');
		
		    $db->Execute($sql);
		    $messageStack->add('review_success','Write a review successfully!','sucess');
		}
	
	}
	
	//Ajax数据提交安全检查，防止恶意行为
	function postCheck($action,$data){
		global $messageStack;
		switch($action){
			case "writeReviews":
				$sql="select * from ".TABLE_REVIEWS." where products_id='".$_GET['products_id']."' and customers_id='".$_SESSION['customer_id']."' and TO_DAYS(date_added) = TO_DAYS(NOW())";
				$rs=openzcQuery($sql);
				if($rs->resource->num_rows >2){
					$messageStack->add('review_product_max','Sorry,Cannot review the same product multiple times in one day！');
					return true;
				}
				$sql="select * from ".TABLE_REVIEWS." where customers_id='".$_SESSION['customer_id']."' and TO_DAYS(date_added) = TO_DAYS(NOW())";
				$rs=openzcQuery($sql);
				if($rs->resource->num_rows >5){
					$messageStack->add('review_customers_max','Sorry,Reviews are too frequent in one day！');
					return true;
				}
				return false;
			break;
		}
	}
	
}
?>